import { SelectHelperVersionChangeHandler } from "./lib/mixinsComponentVersionCache"

export let MixinsPortal = {
  methods: {
    inParamsSetting(item, index) {
      if (!item) return;
      //初始化帮助参数
      item.options.inParams.forEach((param,subIndex) => {
        debugger
        let tempValue = param.DefaultValue
        param.Value = param.Value || ''

        // if(typeof param.Value === 'number'){
        //   param.Value = param.Value + ''
        // }
        let isExpression = !!(param.Value && typeof param.Value === 'string' && param.Value.indexOf(".")!=-1)
                            //&& param.Value.startsWith("{")==false
        
        // if(isExpression){
        //   param.isExpression = isExpression
        //   param.ExpString = param.Value
        // }
        param.isExpression = !!isExpression
        
        if (param.DisplayHelpSetting) {
          let helpSetting = JSON.parse(param.HelpSetting);

          //非表达式，直接用Value
          if(!isExpression && param.ValueType!="Record")tempValue = param.Value

          //处理json字符串（帮助的结果必须是json）
          if(tempValue && typeof tempValue === 'string'){
            try{
              tempValue = JSON.parse(tempValue)
            }catch(e){}
          }

          if(!tempValue && isExpression){
            tempValue = this.$_runParam(param.Value)
          }

          let fieldMapping = [];
          helpSetting.ColumnsMapping.forEach(mapping => {
            if (!mapping.IsShow) return true;
            let fm = {};
            fm.field = mapping.ColCode;
            fm.textAlign = 'left';
            fm.label = Funcs.GetTerms(mapping.ColNameRefSchemaExpr, mapping.ColName, item.Code);
            fieldMapping.push(fm);
          });
          let helperClass = '#paramHelper' + item.InstanceCode + param.Code;
          if (index) helperClass += index;
          
          let _selectHelper =  new selectHelper(helperClass, {
            helperCode: (item.InstanceCode+subIndex),
            value: tempValue[helpSetting.ValueField],
            label: tempValue[helpSetting.DisplayField],
            openSearch: true,
            historySaveCount: 3,
            iconEnable: false,
            countPerPage: 10,
            labelField: helpSetting.DisplayField,
            valueField: helpSetting.ValueField,
            fieldMapping: fieldMapping,
            onOpen: () => {
              SelectHelperVersionChangeHandler(_selectHelper);
            },
            search: function(val, pageIndex, cntPerPage) {
              let parameters = JSON.parse(JSON.stringify(helpSetting.Parameters));
              let sgParamList = [];
              parameters.forEach(parameter => {
                if (parameter.Code == 'PageIndex') {
                  parameter.Value = (pageIndex +1)+ '';
                }
                if (parameter.Code == 'PageSize') {
                  parameter.Value = cntPerPage + '';
                }
                if (parameter.Code == 'DefaultInputFilter') {
                  parameter.Value = val + '';
                }
                sgParamList.push({
                  Order: parameter.Order,
                  ParameterName: parameter.Code,
                  ParameterValue: parameter.Value,
                });
              });
              debugger;
              let sgUrl = Funcs.FasRequestTagAdd(window.FrameSGHost + 'FASR-DQExecute' + '&dqId=' + helpSetting.ActionID);
              if (helpSetting.ActionType == '2') {
                sgUrl = Funcs.FasRequestTagAdd(window.FrameSGHost + 'FASR-ActionExecute' + '&actionId=' + helpSetting.ActionID);
              }
              let postData = {
                parameters:window.Funcs?.Aes256EncryptParams?window.Funcs.Aes256EncryptParams( JSON.stringify(sgParamList)) :JSON.stringify(sgParamList),
              };

              return new Promise((resolve, reject) => {
                window.getDataAsync(
                  sgUrl,
                  'POST',
                  postData,
                  function(result) {
                    debugger;
                    if (result.state == 1) {
                      let _sta = result.data;
                      let data = {
                        rows: _sta.List,
                        total: _sta.Count,
                      };
                      resolve(data);
                    } else {
                      Funcs.HandleError(result.errmsg);
                    }
                  },
                  function(err) {
                    Funcs.HandleError(err);
                  }
                );
              });
            },
            confirm: function(row) {
              debugger;
              
              let name = row[helpSetting.DisplayField];
              let val = row[helpSetting.ValueField];

              if(param.isExpression){
                //_.set(LocalVars, param.Value.replace('LocalVars.',''), row);
                param.DefaultValue = row
              } else {
                  if(param.ValueType=="Record"){
                    //param.Value = row
                    param.DefaultValue = row
                    param.Value = row /** 2023年4月20日 如果不给Value赋值，部件的编辑、设置中的修改无法更新。
                      这段代码在 变更集:227308 备注了 原因未知
                     */ 
                  }else{
                    param.Value = name; //val
                  }
              }
              //param.DefaultValue = row

            },
            onClear: function() {
              //alert(1)
              let row = ''
              if(param.isExpression){
                //_.set(LocalVars, param.Value.replace('LocalVars.',''), row);
                param.DefaultValue = row
              } else {
                  if(param.ValueType=="Record"){
                    param.Value = row
                    param.DefaultValue = row
                  }else{
                    param.Value = ''; //val
                  }
              }
            },
          });
          //if(tempValue[helpSetting.DisplayField])
          _selectHelper.setValue({
            value: (tempValue[helpSetting.ValueField] || ''),
            label: (tempValue[helpSetting.DisplayField] || '')
          })
          /** changeKey: 20230424 2023年4月24日 修复入参帮助赋值
           * 分析：selectHelper内部存在缓存机制，造成复用了之前创建的selectHelper实例
           */
          if (window.SelectHelperInstance[_selectHelper.comID]) {
            delete window.SelectHelperInstance[_selectHelper.comID];
          }
          /** END changeKey: 20230424 */
          // if(isExpression){
          //   _selectHelper.setReadOnly(true)
          // }else{
          //   _selectHelper.setReadOnly(false)
          // }
        }else{
          
          if(isExpression){
            let paramValue = this.$_runParam(param.Value)
            param.Value = paramValue
          }else{
           // param.Value = paramValue
          }
          
        }
      });
    },
    $_runParam(pv) {
      let runExp = TeldFasRTUtils.expression.execute(pv);
      let _val = '';
      if (runExp.state == 1) {
        _val = runExp.result;
      } else {
        _val =pv;
      }
      return _val
    },
  },
};
